package com.sinoglobal.ningxia.thread;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import com.sinoglobal.ningxia.R;


public class LoadImgAsyncTask extends AsyncTask<String, Void, Bitmap> {
	LoadImageAsyncTaskCallBack loadImageAsyncTaskCallBack;
	public static String SD_LOAD_IMG = "sdcard/load/download_img/"; //存放下载下来的图片的地方
	public LoadImgAsyncTask(LoadImageAsyncTaskCallBack loadImageAsyncTaskCallBack){
		this.loadImageAsyncTaskCallBack = loadImageAsyncTaskCallBack;
	}
	public interface LoadImageAsyncTaskCallBack{
		public void beforeLoadImage(); //加载之前，给UI进行初始化的方法
		public void afterLoadImage(Bitmap bitmap); //加载结束之后，更新UI的方法
	}
	@Override
	protected void onPreExecute() {
		//Auto-generated method stub
		super.onPreExecute();
		loadImageAsyncTaskCallBack.beforeLoadImage();
	}
	/**
	 * 根据Url获取app 的名字
	 * 
	 * @param download_url_str
	 * @return
	 */
	public static String getAppName(String download_url_str) {
		int startnum = download_url_str.lastIndexOf("/") + 1;
		String name = download_url_str.substring(startnum,
				download_url_str.length());
		return name;
	}
	@Override
	protected Bitmap doInBackground(String... imgurl) {
		Bitmap bitmap = null;
		try {
			URL url = new URL(imgurl[0]);
			URLConnection urlconn = url.openConnection();
			bitmap = BitmapFactory.decodeStream(urlconn.getInputStream());
			//第一此加载的时候将图片保存到SD卡里面，后面的就直接使用
			String imgname = getAppName(imgurl[0]);
			File f = new File(SD_LOAD_IMG+ imgname);
			if(!f.exists()){
				File f1 = new File(f.getParent());
				if(!f1.exists()){
					f1.mkdirs();
				}
			}
			System.out.println(imgname);
			FileOutputStream fos = null;
			try {
				fos = new FileOutputStream(f);
				bitmap.compress(CompressFormat.JPEG, 100, fos);
			} catch (FileNotFoundException e) {
				//Auto-generated catch block
				e.printStackTrace();
			}finally{
				fos.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return bitmap;
	}
	@Override
	protected void onPostExecute(Bitmap result) {
		super.onPostExecute(result);
		loadImageAsyncTaskCallBack.afterLoadImage(result);
	}
}
